package com.blaze.framework.core.cloud.config;

import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration;
import com.alibaba.cloud.sentinel.feign.SentinelFeign;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.blaze.framework.core.cloud.sentinel.SentinelBlockExceptionHandler;
import feign.Feign;
import feign.RequestInterceptor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * 微服务自动配置
 *
 * @author created by Zhou Zongbo on 2025/5/21.
 */
@AutoConfiguration
@AutoConfigureBefore(SentinelAutoConfiguration.class)
public class BlazeCloudAutoConfiguration {

    /**
     * 构建sentinel feign
     *
     * @param interceptor 请求拦截器
     * @return Feign.Builder
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "feign.sentinel.enabled")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Feign.Builder sentinelFeignBuilder(RequestInterceptor interceptor) {
        return SentinelFeign.builder().requestInterceptor(interceptor);
    }


    /**
     * 触发sentinel限流异常处理器
     *
     * @return BlockExceptionHandler
     */
    @Bean
    @ConditionalOnMissingBean
    public BlockExceptionHandler blockExceptionHandler() {
        return new SentinelBlockExceptionHandler();
    }

}
